const HTTP=require('http')
const FS = require('fs')
const net = require('net');
//内网穿透客户端
var nat = {
    config: {
        serv: {host: '116.255.162.6', port: 8080},//服务器配置
        local: {'116': 8888, wall: 8888, www: 80, md:81},//本地服务名=>端口映射
        retry: 3000,//异常重连
    },
    connServ() {
        var that = this
        let serv =this.serv= net.connect(that.config.serv, () => {
            console.log(`${new Date().toLocaleString()}: NAT已连接服务器`)
            var option = { act: 'regist', name: Object.keys(that.config.local) }
            serv.write(JSON.stringify(option))
        });
        serv.setKeepAlive(true)
        serv.on('data', data => {
            try { data = JSON.parse(data) } catch (err) { return false }
            if (data.act == 'connect') {
                var request = net.connect(that.config.serv, () => {
                    var response = net.connect({ host: '127.0.0.1', port: that.config.local[data.nat] },()=>{
                        response.pipe(request).pipe(response)
                        request.write(JSON.stringify({ act: 'connect', key: data.key }))
                    })
                    request.on('error',err=>{response.end();request.end()})
                    response.on('error',err=>{response.end();request.end()})
                })
            }
        })
        serv.on('error', err => {
            console.log(`${new Date().toLocaleString()}: NAT服务器连接异常:${err.message}`)
            serv.end();
            that.connServ()
        })
        serv.on('end', () => {
            console.log(`${new Date().toLocaleString()}: NAT服务器连接已断开`)
            serv.end();
            that.connServ()
        })
    },
    //定时监测连接状态&&断线重连
    run(){
        var that = this
        that.connServ()
        setInterval(() => {
            if (that.serv.readyState != 'open') {
                that.serv.end()
                that.connServ()
            }
        }, that.config.retry)
    }
}
nat.run();